package com.mss.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mss.media.dto.AuditCaseDTO;
import com.mss.media.dto.PageDTO;
import com.mss.media.entity.CaseAuditList;
import com.mss.media.entity.MediaCase;
import com.mss.media.entity.MediaCaseContent;
import com.mss.media.entity.MediaClassification;
import com.mss.media.mapper.CaseAuditListMapper;
import com.mss.media.mapper.MediaCaseContentMapper;
import com.mss.media.mapper.MediaCaseMapper;
import com.mss.media.mapper.MediaClassificationMapper;
import com.mss.media.service.ICaseAuditListService;
import com.mss.media.service.IMediaAdminService;
import com.mss.media.util.abnormal.MssException;
import com.mss.media.vo.CaseAuditPageVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 审核列表 服务实现类
 * </p>
 *
 * @author runqiang
 * @since 2021-12-01
 */
@Service
@Transactional(rollbackFor = MssException.class)
public class CaseAuditListServiceImpl extends ServiceImpl<CaseAuditListMapper, CaseAuditList> implements ICaseAuditListService {

    @Autowired
    private CaseAuditListMapper caseAuditListMapper;
    @Autowired
    private IMediaAdminService mediaAdminService;
    @Autowired
    private MediaClassificationMapper mediaClassificationMapper;
    @Autowired
    private MediaCaseMapper mediaCaseMapper;
    @Autowired
    private MediaCaseContentMapper mediaCaseContentMapper;

    /**
     * 审核作品
     *
     * @param dto 审核信息
     * @return
     */
    @Override
    public Boolean auditCase(AuditCaseDTO dto, HttpServletRequest request) {
        if (ObjectUtils.isEmpty(dto)) {
            throw new MssException("参数不能为空");
        }
        String adminAccount = mediaAdminService.parsingAccount(request);
        LocalDateTime now = LocalDateTime.now();
        LambdaUpdateWrapper<CaseAuditList> wrapper = Wrappers.lambdaUpdate();
        wrapper.set(CaseAuditList::getAuditTime, now);
        wrapper.set(CaseAuditList::getAdminAccount, adminAccount);
        wrapper.set(CaseAuditList::getAuditStatus, dto.getAuditStatus());
        if (dto.getAuditStatus() == 2) {
            wrapper.set(CaseAuditList::getNotPassCause, dto.getNotPassCause());
        }
        wrapper.eq(CaseAuditList::getAuditId, dto.getAuditId());
        CaseAuditList caseAuditList = caseAuditListMapper.selectById(dto.getAuditId());
        if (ObjectUtils.isEmpty(caseAuditList)) {
            throw new MssException("未查询到作品，请稍后重试！");
        }
        int update = caseAuditListMapper.update(caseAuditList, wrapper);
        if (update <= 0) {
            throw new MssException("系统错误，审核失败！");
        }
        MediaCase mediaCase = mediaCaseMapper.selectById(caseAuditList.getCaseId());
        if (ObjectUtils.isEmpty(mediaCase)) {
            throw new MssException("未查询到作品，请稍后重试！");
        }
        LambdaUpdateWrapper<MediaCase> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(MediaCase::getAuditStatus, dto.getAuditStatus());
        updateWrapper.set(MediaCase::getAuditTime, now);
        updateWrapper.eq(MediaCase::getCaseId, caseAuditList.getCaseId());
        int update1 = mediaCaseMapper.update(mediaCase, updateWrapper);
        if (update1 <= 0) {
            throw new MssException("系统错误，审核失败！");
        }
        return true;
    }

    /**
     * 分页查询作品审核列表
     *
     * @param dto 页码
     * @return 作品审核列表
     */
    @Override
    public IPage<CaseAuditPageVO> findAllPage(PageDTO dto) {
        if (ObjectUtils.isEmpty(dto)) {
            dto = new PageDTO();
            dto.setLimit(10)
                    .setPage(1);
        }
        if (dto.getPage() == null) {
            dto.setPage(1);
        }
        if (dto.getLimit() == null) {
            dto.setLimit(10);
        }
        Page<CaseAuditList> page = new Page<>(dto.getPage(), dto.getLimit());
        IPage<CaseAuditPageVO> allPage = caseAuditListMapper.findAllPage(dto.getSubmitTime(), dto.getAuditTime(), dto.getCaseType(), dto.getAudit(), page);
        List<MediaClassification> mediaClassifications = mediaClassificationMapper.selectList(null);
        Map<Integer, String> collect = mediaClassifications.stream()
                .collect(Collectors.toMap(MediaClassification::getClassificationId,
                        MediaClassification::getClassificationName));
        List<CaseAuditPageVO> records = allPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return allPage;
        }
        StringBuilder labels = null;
        for (CaseAuditPageVO record : records) {
            String[] splitLabelIds = record.getLabelId().split(",");
            labels = new StringBuilder();
            for (String labelId : splitLabelIds) {
                labels.append(collect.get(Integer.valueOf(labelId)));
                labels.append(",");
            }
            labels.deleteCharAt(labels.length() - 1);
            record.setLabelId(labels.toString());
        }
        allPage.setRecords(records);
        return allPage;
    }

    /**
     * 查看审核作品信息
     *
     * @param caseId 作品ID
     * @return 作品信息
     */
    @Override
    public List<String> findAuditCaseId(Long caseId) {
        if (caseId == null) {
            throw new MssException("未识别到作品，请稍后重试！");
        }
        MediaCase mediaCase = mediaCaseMapper.selectById(caseId);
        if (ObjectUtils.isEmpty(mediaCase)) {
            throw new MssException("未查询到作品，请稍后重试！");
        }
        LambdaQueryWrapper<MediaCaseContent> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(MediaCaseContent::getCaseId, caseId);
        List<MediaCaseContent> contents = mediaCaseContentMapper.selectList(wrapper);
        if (ObjectUtils.isEmpty(contents)) {
            throw new MssException("该作品无资源信息");
        }
        List<String> address = new ArrayList<>();
        for (MediaCaseContent content : contents) {
            String[] splits = content.getResourceAddress().split(";");
            address.addAll(Arrays.asList(splits));
        }
        return address;
    }
}
